'use strict';

/**
 * 获取1位随机数
 * @param {Number} min
 * @param {Number} max
 * @return {Number} 随机数字
 */
const getRandom = (min, max) => {
  return Math.round(Math.random() * max) + min;
};

/**
 * 获取多位随机数
 * @param {Number} num
 * @return {Number} 随机数字
 */
const getLengthRandom = len => {
  let num = '';
  while (num.length < len) {
    num += getRandom(0, 9);
  }
  return num;
};

const arrayToTree = array => {
  const json = {};
  const newArray = [];
  array.forEach(item => {
    json[item.id] = item;
  });
  array.forEach(item => {
    if (item.parent_id === 0) {
      newArray.push(item);
    } else {
      const parent = json[item.parent_id];
      if (parent.children) {
        parent.children.push(item);
      } else {
        parent.children = [ item ];
      }
    }
  });
  return newArray;
};

module.exports = {
  getRandom,
  getLengthRandom,
  arrayToTree,
};
